package com.azxc.rapid.auth.granter;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.azxc.rapid.auth.constant.AuthConstant;
import com.azxc.rapid.auth.service.RapidUserDetails;
import com.azxc.rapid.auth.utils.TokenUtil;
import com.azxc.rapid.core.log.exception.ServiceException;
import com.azxc.rapid.core.redis.cache.RapidRedis;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.support.Kv;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.core.tool.utils.StringUtil;
import com.azxc.rapid.core.tool.utils.WebUtil;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.entity.UserInfo;
import com.azxc.rapid.system.user.feign.IUserClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author linym
 * @className: WestoneGranter
 * @description:
 * @date 2023/1/16 10:05
 * @version：1.0
 */
@Slf4j
public class PortalGranter extends AbstractTokenGranter {
	private static final String GRANT_TYPE = "portal";
	private final IUserClient userClient;


	private final String clientId;

	private final String clientSecret;

	private final String portalUrl;

	private final String redirectUri;


	private RapidRedis rapidRedis;

	/*App Key：APPAD3BADB33B0622F1BE4C0E5A

	App Secret：0oRkwKpQn62jGsTT_cgK5C8a4p0bfiJ49_hsYqrJ49JN4z8q4U_J4Trf8dOu6N0dQU4

	Corp Secret：a1024mo37JlrK3u2_MR7yNv8rKXsGD819_sNsrJZ4Ubg0zSi5y_0k568xPRQ7TIe951*/

	protected PortalGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IUserClient userClient,
                             String clientId, String clientSecret,String portalUrl,String redirectUri) {
		super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.userClient = userClient;
		this.clientId = clientId;
		this.clientSecret = clientSecret;
		this.portalUrl = portalUrl;
		this.redirectUri = redirectUri;
	}



	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		HttpServletRequest request = WebUtil.getRequest();


		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		String code = parameters.get("code");
		if(StringUtil.isEmpty(code)){
			throw new InvalidGrantException("缺少参数oauth_code！");

		}
	 	log.info("进入");

		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		RapidUserDetails rapidUserDetails;
		String tele = "";
		//根据access_token
		try {
			String url = portalUrl+"/oauth/token?client_id="+clientId+"&client_secret="+clientSecret+"&grant_type=authorization_code&redirect_uri="+redirectUri+"&code="+code;
			log.info("url:"+url);
			log.debug("url:"+url);
			String r = HttpUtil.get(url);
			log.info("r:"+r);
			log.debug("r:"+r);
			JSONObject jobject = JSONObject.parseObject(r);
			String url2 = portalUrl+"/oauth/userinfo?access_token="+jobject.getString("access_token");
			log.info("url2:"+url2);
			log.debug("url2:"+url2);
			String r2 = HttpUtil.get(url2);
			log.info("r2:"+r2);
			log.debug("r2:"+r2);
 			JSONObject jobject2 = JSONObject.parseObject(r2);
			log.info("jobject2:"+jobject2);
			 //根据用户名获取用户信息
			tele = jobject2.getString("phone_number");
			if(StringUtil.isEmpty(tele)){
				throw new ServiceException("请求统一门户接口失败！");
			}
		}catch (Exception ex ){
			logger.error(ex);
			throw new InvalidGrantException("调用统一门户接口失败！");
		}
		// 远程调用，获取认证信息
		// 远程调用，获取认证信息
		R<UserInfo> result = userClient.userInfoByPhone(tenantId,tele);
		//R<UserInfo> result = userClient.userInfo(tenantId,account);

		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null) {
				throw new InvalidGrantException("统一门户登录失败，未找到该用户");
			}
			rapidUserDetails = new RapidUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()),null,
				user.getAccount(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("portal grant failure, feign client return error");
		}


		Authentication userAuth = new UsernamePasswordAuthenticationToken(rapidUserDetails, null, rapidUserDetails.getAuthorities());
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

		// 返回 OAuth2Authentication
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}


}
